package com.ak.server.log.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ak.common.annotation.LogEndpoint;
import com.ak.common.entity.AKResponse;
import com.ak.common.entity.QueryRequest;
import com.ak.common.utils.AKUtil;
import com.ak.server.log.entity.LoginLog;
import com.ak.server.log.service.ILoginLogService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;

/**
 * @author Vean
 */
@Api(tags = "登录日志模块")
@RestController
@RequestMapping("loginLog")
@RequiredArgsConstructor
public class LoginLogController {

    private final ILoginLogService loginLogService;

    @GetMapping
    public AKResponse loginLogList(LoginLog loginLog, QueryRequest request) {
        Map<String, Object> dataTable = AKUtil.getDataTable(this.loginLogService.findLoginLogs(loginLog, request));
        return new AKResponse().data(dataTable);
    }

    @GetMapping("currentUser")
    public AKResponse getUserLastSevenLoginLogs() {
        String currentUsername = AKUtil.getCurrentUsername();
        List<LoginLog> userLastSevenLoginLogs = this.loginLogService.findUserLastSevenLoginLogs(currentUsername);
        return new AKResponse().data(userLastSevenLoginLogs);
    }

    @DeleteMapping("{ids}")
    @PreAuthorize("hasAuthority('loginlog:delete')")
    @LogEndpoint(operation = "删除登录日志", exceptionMessage = "删除登录日志失败")
    public void deleteLogs(@NotBlank(message = "{required}") @PathVariable String ids) {
        String[] loginLogIds = ids.split(StringPool.COMMA);
        this.loginLogService.deleteLoginLogs(loginLogIds);
    }

    @PostMapping("excel")
    @PreAuthorize("hasAuthority('loginlog:export')")
    @LogEndpoint(operation = "导出登录日志数据", exceptionMessage = "导出Excel失败")
    public void export(QueryRequest request, LoginLog loginLog, HttpServletResponse response) {
        List<LoginLog> loginLogs = this.loginLogService.findLoginLogs(loginLog, request).getRecords();
        ExcelKit.$Export(LoginLog.class, response).downXlsx(loginLogs, false);
    }
}
